<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2016/12/28
 * Time: 11:59
 */
namespace AuctionBack\Controller;

use AuctionBack\Logic\ProceduresLogic;
use AuctionCore\Common\Util;
use AuctionCore\System\AuctionException;
use AuctionBack\Logic\ProceduresRequirementLogic;
use AuctionCore\Common\PhpRedis;
use AuctionCore\Company\CompanyManage;

class ProceduresController extends BaseController
{


    public function __construct()
    {
        parent::__construct();
        //分公司
        $bc_list = $this->get_branch_company_list();
        $this->assign('bc_list', $bc_list);
    }

    /**
     * 手续默认页
     */
    public function index()
    {
        $this->display();
    }

    /**
     * 获取手续列表
     */
    public function getList()
    {
        $uploadStatus = I('get.upload_status');
        $page = I("get.p/d", 1);
        $bc_city = I('get.bc_city');

        $location_area = [];
        if ($bc_city) {
            $cityInfo = CompanyManage::getCityCodeByBranchId($bc_city);
            foreach ($cityInfo as $key => $value) {
                $location_area[] = $value['city_code'];
            }
        } else {
            $location_area = $this->user_info['bc_code'];
        }

        $params['location_area'] = $location_area;
        $size = 10;
        $params ['upload_status'] = $uploadStatus;

        $params['car_plate_number'] = trim(I("get.car_plate_number", ''));
        $params['sno'] = trim(I("get.sno", ''));
        $result = ProceduresLogic::getList($page, $size, $params);
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出

        //模板赋值
        $this->assign('status', $uploadStatus);
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign("params", $params);
        $this->display('Procedures/procedures_list');
    }

    /**
     * 获取手续详情
     */
    public function procedures_info()
    {
        $id = I('get.id');
        $uploadStatus = I('get.status');
        $proceduresObj = new ProceduresLogic($id);
        $detail = $proceduresObj->detail();

        $orderId = $detail['order_id'];
        $redis = new PhpRedis(0);

        $arr = [
            'order_id'=>$orderId,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100005',$arr);
        $redis->getRedis()->del($keyName); //重新加载页面时，删掉原来的缓存信息
        //$redis->getRedis()->del('transfer_procedures_' . $orderId); //重新加载页面时，删掉原来的缓存信息
        $redis->getRedis()->close();


        //获取手续上传要求
        $prLogic = new ProceduresRequirementLogic($detail['sid']);
        $beforeTransfer = $prLogic->getListByTransferStatus(1);
        $afterTransfer = $prLogic->getListByTransferStatus(2);
        $this->assign('beforeTransfer', $beforeTransfer);
        $this->assign('afterTransfer', $afterTransfer);
        $this->assign('status', $uploadStatus);
        $this->assign('detail', $detail);
        $this->display();
    }


    /**
     * 上传图片
     */
    public function upload()
    {
        $certificateId = I('post.certificate_id');;
        $orderId = I('post.order_id');
        $type = I('post.type');
        $pic = $_FILES['file'];
        $order_no = I('post.order_no');
        $size = $pic['size'];
        $maxSize = 4 * 1024 * 1024;
        //尾缀验证图片类型
        $ext = strtolower(get_extension($pic['name']));
        $allow_image_types = array('jpg', 'png', 'jpeg');
//		if ($size > $maxSize) {
//			echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 500, 'msg' => '图片不能超过5M'));
//			exit;
//		}
        if (!in_array($ext, $allow_image_types)) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 501, 'msg' => '上传图片格式不正确'));
            exit;
        }

        if (!empty($pic)) {
            $flag = true;
            if ($pic['error'] != 0) {
                $flag = false;
                $rep['msg'] = '照片上传失败';
                \Think\Log::record($rep['msg'] . ',错误码：' . $pic['error'] . ',time:' . date('Y-m-d H:i:s'));
            }
            //图片上传
            if ($flag) {
                $res = move_uploaded_file($pic['tmp_name'], "/tmp/" . $pic['name']);
                $object = 'upload/' . create_uuid() . '.' . get_extension($pic['name']);
                //$tmp_path = '/tmp/' . create_uuid() . '.' . get_extension($pic['name']);
                $tmp_path = '/tmp/' . $pic['name'];
                // $pic_path = $pic['tmp_name'];

                try {
                    $aliObject = \AuctionCore\Common\Image::upload_file_by_file(OSS_BUCKET, $object, $tmp_path, null, '', 'procedure/' . $order_no, true);
                    //dump($aliObject);die();
                    $redis = new PhpRedis(0);

                    $arr = [];
                    $keyArr = [
                        'order_id'=>$orderId,
                    ];
                    $keyName = getRedisKeyByCode('REDIS_KEY','100005',$keyArr);
                    $list = $redis->getRedis()->get($keyName);
                    //$list = $redis->getRedis()->get('transfer_procedures_' . $orderId);
                    if (!empty($list)) {
                        $arr = json_decode($list, true);
                    }

                    //foreach ($arr as )

                    if ($aliObject) {
                        $data['url'] = $aliObject;
                        $data['order_id'] = $orderId;
                        $data['type'] = $type;
                        $data['certificate_id'] = $certificateId;
                        $data['createtime'] = date('Y-m-d H:i:s');
                        $data['action'] = 'add';

                        $arr[$aliObject] = $data;
                        $keyArr = [
                            'order_id'=>$orderId,
                        ];
                        $keyName = getRedisKeyByCode('REDIS_KEY','100005',$keyArr);
                        $result = $redis->getRedis()->set($keyName, json_encode($arr), 3600 * 24);
                        //$result = $redis->getRedis()->set('transfer_procedures_' . $orderId, json_encode($arr), 3600 * 24);
                        if (!$result) {
                            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 422, 'msg' => '上传失败', 'data' => '写入Redis失败'));
                            exit;
                        }
                        /*$transfer_img = M("transfer_img");
                        $img_id = $transfer_img->data($data)->add();*/
                    }
                    $host = get_content_cdnurl();
                    $url = $host . $aliObject;
                    //dump($url);die();
                    $arr = array(
                        'pic' => $url,
                        'img_id' => '0',
                        'data_url' => $aliObject,
                    );
                    //删除压缩后的临时文件
                    @unlink("/tmp/" . $pic['name']);

                    /*$redis = new PhpRedis(1);
                    $redis->getRedis()->lRem('transfer_procedures',$orderId,0);
                    $result = $redis->getRedis()->lPush('transfer_procedures',$orderId);
                    if(!$result){
                        M()->rollback();
                        echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 422, 'msg' => '写入Redis失败', 'data' => ''));
                        exit;
                    }*/


                    echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => $arr));
                    exit;
                } catch (AuctionException $e) {
                    echo Util::auto_jsonp_or_json($_REQUEST, array('msg' => $e->getMessage(), 'code' => $e->getCode()));
                    exit;
                }
            }
        }
    }

    /**
     * 确认上传成功
     */
    public function save()
    {
        $id = I('post.id');
        $order_id = I('post.order_id');

        $redis = new PhpRedis(0);
        $keyArr = [
            'order_id'=>$order_id,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100005',$keyArr);
        $list = $redis->getRedis()->get($keyName);
        //$list = $redis->getRedis()->get('transfer_procedures_' . $order_id);
        M()->startTrans();
        if (!empty($list)) {
            $arr = json_decode($list, true);
            foreach ($arr as $key => $value) {
                $action = $value['action'];
                if ($action == 'add') {
                    $transfer_img = M("transfer_img");
                    $img_id = $transfer_img->data($value)->add();
                    if (!$img_id) {
                        M()->rollback();
                        echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 422, 'msg' => '操作失败', 'data' => '添加图片'));
                        exit;
                    }
                } else {
                    $img_id = $value['img_id'];
                    if ($img_id >= 1) {
                        $del = M('transfer_img')->where("id=" . $img_id)->delete();
                        if (!$del) {
                            M()->rollback();
                            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 422, 'msg' => '操作失败', 'data' => '删除图片'));
                            exit;
                        }
                    } else {
                        throw new AuctionException('操作非法！');
                    }
                }
            }

            $logData['zip_url'] = '';
            $result = M('transfer_log')->where(['order_id' => $order_id])->save($logData);
            if ($result === false) {
                M()->rollback();
                $this->helpJsonResult('422', '更新过户信息失败!');
            }
        }

        $data = [
            'emp_id' => $this->user_info['emp_id'],
            'emp_name' => $this->user_info['real_name'],
            'upload_status' => '1',
            'upload_time' => date('Y-m-d H:i:s', time()),
        ];

        $proceduresObj = new ProceduresLogic($id);
        $result = $proceduresObj->save($data);

        if (!$result) {
            M()->rollback();
            $this->helpJsonResult('422', '操作失败!', '更新手续信息');
        }

        M()->commit();

        $keyName = getRedisKeyByCode('REDIS_KEY','100019',[]);
        $redis->getRedis()->lRem($keyName, $order_id, 0);
        $result = $redis->getRedis()->lPush($keyName, $order_id);
        if (!$result) {
            echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 422, 'msg' => '操作失败', 'data' => '写入redis失败'));
        }
        $keyArr = [
            'order_id'=>$order_id,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100005',$keyArr);
        $redis->getRedis()->del($keyName);
        //$redis->getRedis()->del('transfer_procedures_' . $order_id);
        echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '操作成功', 'data' => ''));
        exit;

    }

    /**
     * 删除图片
     */
    public function deleteImg()
    {

        $id = I('post.img_id');
        $orderId = I('post.order_id');
        $data_url = I('post.image_url');

        $redis = new PhpRedis(0);
        $keyArr = [
            'order_id'=>$orderId,
        ];
        $keyName = getRedisKeyByCode('REDIS_KEY','100005',$keyArr);
        $list = $redis->getRedis()->get($keyName);
        //$list = $redis->getRedis()->get('transfer_procedures_' . $orderId);
        $arr = [];
        if (!empty($list)) {
            $arr = json_decode($list, true);

            $result = array_key_exists($data_url, $arr);
            if ($result) {
                unset($arr[$data_url]);
                $keyArr = [
                    'order_id'=>$orderId,
                ];
                $keyName = getRedisKeyByCode('REDIS_KEY','100005',$keyArr);
                $result = $redis->getRedis()->set($keyName, json_encode($arr), 3600 * 24);
                //$result = $redis->getRedis()->set('transfer_procedures_' . $orderId, json_encode($arr), 3600 * 24);
                if (!$result) {
                    echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 422, 'msg' => '删除失败', 'data' => ''));
                    exit;
                }
            }
        }

        if ($id) {
            $data['img_id'] = $id;
            $data['action'] = 'del';
            $arr[$data_url] = $data;
            $keyArr = [
                'order_id'=>$orderId,
            ];
            $keyName = getRedisKeyByCode('REDIS_KEY','100005',$keyArr);
            $result = $redis->getRedis()->set($keyName, json_encode($arr), 3600 * 24);
            //$result = $redis->getRedis()->set('transfer_procedures_' . $orderId, json_encode($arr), 3600 * 24);
            if (!$result) {
                echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 422, 'msg' => '删除失败', 'data' => ''));
                exit;
            }
        }

        echo Util::auto_jsonp_or_json($_REQUEST, array('code' => 200, 'msg' => '', 'data' => ''));
        exit;
    }
}